import pandas as pd
import xgboost as xgb
from sklearn.metrics import accuracy_score, confusion_matrix, classification_report

# 1. 读取训练集和测试集数据
train_data = pd.read_csv("C:\\Users\\董柳蕙\\Downloads\\heart.csv")  # 训练集
test_data = pd.read_csv('D:\\heart_cleaned.csv')  # 测试集

# 2. 分离训练集的特征和目标列
X_train = train_data.drop(columns=['target'])  # 训练特征
y_train = train_data['target']  # 训练目标

# 确保测试集的特征和训练集的列名一致
X_test = test_data[X_train.columns]

# 3. 训练 XGBoost 模型
model = xgb.XGBClassifier(use_label_encoder=False, eval_metric='logloss')  # 使用XGBoost分类器
model.fit(X_train, y_train)  # 训练模型

# 4. 模型预测
y_pred = model.predict(X_test)  # 预测测试集

# 5. 保存预测结果到CSV文件
output = X_test.copy()  # 拷贝测试特征数据
output['predicted_target'] = y_pred  # 添加预测结果列
output.to_csv('D:\\heart_predictions.csv', index=False)  # 保存结果

print("预测结果已保存为 'heart_predictions.csv'")

# 6. 模型性能分析（基于训练集交叉验证）
y_train_pred = model.predict(X_train)

# 评估指标
print("\n模型在训练集上的表现：")
print("准确率：", accuracy_score(y_train, y_train_pred))  # 准确率
print("\n混淆矩阵：")
print(confusion_matrix(y_train, y_train_pred))  # 混淆矩阵
print("\n分类报告：")
print(classification_report(y_train, y_train_pred))  # 分类报告
